<template>
  <div class="role-management">
    <div class="page-header">
      <h2>{{ $t('common.roleManagement') }}</h2>
      <p>{{ $t('common.roleManagementDescription') }}</p>
    </div>
    
    <div class="search-container">
      <div class="search-item">
        <label>{{ $t('role.roleName') }}:</label>
        <InputText v-model="searchParams.roleName" placeholder="{{ $t('common.pleaseInput') }}" />
      </div>
      <div class="search-item">
        <label>{{ $t('role.status') }}:</label>
        <Dropdown
          v-model="searchParams.status"
          :options="statusOptions"
          placeholder="{{ $t('common.pleaseSelect') }}"
          optionValue="value"
          optionLabel="label"
        />
      </div>
      <div class="search-actions">
        <Button @click="search" icon="pi pi-search">{{ $t('common.search') }}</Button>
        <Button @click="reset" icon="pi pi-refresh">{{ $t('common.reset') }}</Button>
        <Button @click="handleAdd" icon="pi pi-plus" severity="success">{{ $t('common.add') }}</Button>
      </div>
    </div>
    
    <div class="table-container">
      <DataTable
        :value="roleStore.getRoleList"
        :loading="roleStore.getLoading"
        :paginator="true"
        :rows="searchParams.pageSize"
        :first="(searchParams.page - 1) * searchParams.pageSize"
        :totalRecords="roleStore.getRoleTotal"
        @page="onPageChange"
        @sort="onSortChange"
        rowHover
      >
        <Column selectionMode="multiple" headerStyle="width: 3rem"></Column>
        <Column field="id" header="{{ $t('role.roleId') }}" sortable></Column>
        <Column field="roleName" header="{{ $t('role.roleName') }}" sortable></Column>
        <Column field="roleKey" header="{{ $t('role.roleKey') }}" sortable></Column>
        <Column field="roleSort" header="{{ $t('role.roleSort') }}" sortable></Column>
        <Column field="dataScope" header="{{ $t('role.dataScope') }}" sortable>
          <template #body="{ data }">
            {{ getRoleDataScope(data.dataScope) }}
          </template>
        </Column>
        <Column field="status" header="{{ $t('common.status') }}">
          <template #body="{ data }">
            <Badge :severity="data.status === 1 ? 'success' : 'danger'">
              {{ data.status === 1 ? $t('common.active') : $t('common.inactive') }}
            </Badge>
          </template>
        </Column>
        <Column field="createTime" header="{{ $t('common.createTime') }}" sortable></Column>
        <Column header="{{ $t('common.operate') }}" style="width: 15rem">
          <template #body="{ data }">
            <Button @click="handleEdit(data)" icon="pi pi-pencil" size="small"></Button>
            <Button @click="handleDelete(data.id)" icon="pi pi-trash" size="small" severity="danger"></Button>
            <Button @click="handleAssignPermission(data.id)" icon="pi pi-lock" size="small" severity="info"></Button>
            <Button @click="handleAssignUser(data.id)" icon="pi pi-users" size="small" severity="warning"></Button>
          </template>
        </Column>
      </DataTable>
    </div>
    
    <!-- 批量操作 -->
    <div class="batch-actions" v-if="selectedRoles.length > 0">
      <span>{{ $t('common.selected') }} {{ selectedRoles.length }} {{ $t('common.items') }}</span>
      <Button @click="handleBatchDelete" severity="danger">{{ $t('common.batchDelete') }}</Button>
    </div>
    
    <!-- 添加/编辑对话框 -->
    <Dialog v-model:visible="dialogVisible" :header="dialogTitle" :modal="true" :style="{ width: '500px' }">
      <div class="form-container">
        <div class="form-item">
          <label>{{ $t('role.roleName') }} *:</label>
          <InputText v-model="formData.roleName" />
        </div>
        <div class="form-item">
          <label>{{ $t('role.roleKey') }} *:</label>
          <InputText v-model="formData.roleKey" />
        </div>
        <div class="form-item">
          <label>{{ $t('role.roleSort') }} *:</label>
          <InputNumber v-model="formData.roleSort" min="1" :max="999" />
        </div>
        <div class="form-item">
          <label>{{ $t('role.dataScope') }} *:</label>
          <Dropdown
            v-model="formData.dataScope"
            :options="dataScopeOptions"
            optionValue="value"
            optionLabel="label"
          />
        </div>
        <div class="form-item">
          <label>{{ $t('role.status') }} *:</label>
          <Dropdown
            v-model="formData.status"
            :options="statusOptions"
            optionValue="value"
            optionLabel="label"
          />
        </div>
        <div class="form-item">
          <label>{{ $t('role.remark') }}:</label>
          <Textarea v-model="formData.remark" rows="3" />
        </div>
      </div>
      <template #footer>
        <Button @click="dialogVisible = false">{{ $t('common.cancel') }}</Button>
        <Button @click="handleSave" severity="primary">{{ $t('common.submit') }}</Button>
      </template>
    </Dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoleStore } from '../../../store/modules/system/role'
import type { Role } from '../../../types/app.d'
import Button from 'primevue/button'
import InputText from 'primevue/inputtext'
import InputNumber from 'primevue/inputnumber'
import Textarea from 'primevue/textarea'
import Dropdown from 'primevue/dropdown'
import DataTable from 'primevue/datatable'
import Column from 'primevue/column'
import Badge from 'primevue/badge'
import Dialog from 'primevue/dialog'

const { t } = useI18n()
const roleStore = useRoleStore()

// 搜索参数
const searchParams = reactive({
  page: 1,
  pageSize: 10,
  roleName: '',
  status: null as number | null
})

// 状态选项
const statusOptions = [
  { label: t('common.active'), value: 1 },
  { label: t('common.inactive'), value: 0 }
]

// 数据范围选项
const dataScopeOptions = [
  { label: t('role.dataScopeAll'), value: 1 },
  { label: t('role.dataScopeCustom'), value: 2 },
  { label: t('role.dataScopeDept'), value: 3 },
  { label: t('role.dataScopeDeptAndBelow'), value: 4 },
  { label: t('role.dataScopeSelf'), value: 5 }
]

// 选中的角色
const selectedRoles = ref<Role[]>([])

// 对话框状态
const dialogVisible = ref(false)
const isEdit = ref(false)
const dialogTitle = ref('')

// 表单数据
const formData = reactive<Partial<Role>>({
  roleName: '',
  roleKey: '',
  roleSort: 0,
  dataScope: 1,
  status: 1,
  remark: ''
})

// 初始化
const init = () => {
  roleStore.getRoleListAction(searchParams)
}

// 获取角色数据范围文本
const getRoleDataScope = (dataScope: number) => {
  const scope = dataScopeOptions.find(option => option.value === dataScope)
  return scope ? scope.label : ''
}

// 搜索
const search = () => {
  searchParams.page = 1
  roleStore.getRoleListAction(searchParams)
}

// 重置
const reset = () => {
  Object.assign(searchParams, {
    page: 1,
    pageSize: 10,
    roleName: '',
    status: null
  })
  roleStore.getRoleListAction(searchParams)
}

// 页面变化
const onPageChange = (event: any) => {
  searchParams.page = event.page + 1
  searchParams.pageSize = event.rows
  roleStore.getRoleListAction(searchParams)
}

// 排序变化
const onSortChange = (event: any) => {
  // 实际项目中可以根据排序字段和方向进行排序
  roleStore.getRoleListAction(searchParams)
}

// 添加角色
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = t('common.add') + t('common.role')
  Object.assign(formData, {
    roleName: '',
    roleKey: '',
    roleSort: 0,
    dataScope: 1,
    status: 1,
    remark: ''
  })
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = async (role: Role) => {
  isEdit.value = true
  dialogTitle.value = t('common.edit') + t('common.role')
  await roleStore.getRoleInfoAction(role.id)
  if (roleStore.getCurrentRole) {
    Object.assign(formData, roleStore.getCurrentRole)
  }
  dialogVisible.value = true
}

// 保存角色
const handleSave = async () => {
  if (isEdit.value && formData.id) {
    const success = await roleStore.updateRoleAction(formData.id, formData)
    if (success) {
      dialogVisible.value = false
      roleStore.getRoleListAction(searchParams)
      roleStore.clearCurrentRole()
    }
  } else {
    const success = await roleStore.createRoleAction(formData as Omit<Role, 'id' | 'createTime' | 'updateTime'>)
    if (success) {
      dialogVisible.value = false
      roleStore.getRoleListAction(searchParams)
    }
  }
}

// 删除角色
const handleDelete = async (id: string) => {
  if (confirm(t('common.confirmDelete'))) {
    const success = await roleStore.deleteRoleAction(id)
    if (success) {
      roleStore.getRoleListAction(searchParams)
    }
  }
}

// 批量删除角色
const handleBatchDelete = async () => {
  if (confirm(t('common.confirmBatchDelete'))) {
    const ids = selectedRoles.value.map(role => role.id)
    const success = await roleStore.batchDeleteRoleAction(ids)
    if (success) {
      selectedRoles.value = []
      roleStore.getRoleListAction(searchParams)
    }
  }
}

// 分配权限
const handleAssignPermission = (id: string) => {
  // 实际项目中可以打开权限分配对话框
  // 分配权限给角色
}

// 分配用户
const handleAssignUser = (id: string) => {
  // 实际项目中可以打开用户分配对话框
  // 分配用户给角色
}

// 初始化加载数据
init()
</script>

<style scoped>
.role-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #333;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.search-container {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  flex-wrap: wrap;
  align-items: flex-end;
}

.search-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.search-item label {
  font-weight: 500;
  color: #333;
}

.search-actions {
  display: flex;
  gap: 8px;
  margin-left: auto;
}

.table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.batch-actions {
  margin-top: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.form-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.form-item label {
  font-weight: 500;
  color: #333;
}

.form-item input,
.form-item select,
.form-item .p-inputnumber,
.form-item .p-inputtextarea {
  width: 100%;
}
</style>